<template>
	<view class="page">
		<up-sticky>
			<view class="top-bg">
				<view class="status-bar" :style="{ 'paddingTop': statusBarHeight + 'px' }"></view>
				<view class="nav-bar">
					<!-- 搜索栏 -->
					<view class="search-box">
						<up-search placeholder="输入套系名称搜索" v-model="keyword" :show-action="false" :clearabled="true"
							:disabled="true" @click="toSearch"></up-search>
					</view>
				</view>
			</view>
			<!-- 筛选项 -->
			<view class="dropdown-box">
				<up-dropdown ref="filterRef" active-color="#E7B796">
					<!-- 地点 -->
					<up-dropdown-item v-model="filters.location" :title="locationText">
						<view class="slot-content">
							<scroll-view scroll-y="true">
								<up-row gutter="10">
									<up-col span="3" v-for="(item, index) of filterData.options1" :key="index"
										@click="clickSelect(0, item)">
										<view class="select up-line-1"
											:class="{'active': filters.location == item.dictValue}">{{ item.dictLabel }}
										</view>
									</up-col>
								</up-row>
							</scroll-view>
						</view>
					</up-dropdown-item>
					<!-- 性别 -->
					<up-dropdown-item v-model="filters.sex" :title="sexText">
						<view class="slot-content">
							<scroll-view scroll-y="true">
								<up-row gutter="10">
									<up-col span="3" v-for="(item, index) of filterData.options4" :key="index"
										@click="clickSelect(3, item)">
										<view class="select up-line-1" :class="{'active': filters.sex == item.dictValue}">
											{{ item.dictLabel }}</view>
									</up-col>
								</up-row>
							</scroll-view>
						</view>
					</up-dropdown-item>
					<!-- 角色 -->
					<up-dropdown-item v-model="filters.category" :title="categoryText">
						<view class="slot-content">
							<scroll-view scroll-y="true">
								<up-row gutter="10">
									<up-col span="3" v-for="(item, index) of filterData.options2" :key="index"
										@click="clickSelect(1, item)">
										<view class="select up-line-1"
											:class="{'active': filters.category == item.dictValue}">{{ item.dictLabel }}
										</view>
									</up-col>
								</up-row>
							</scroll-view>
						</view>
					</up-dropdown-item>
					<!-- 排序 -->
					<up-dropdown-item v-model="filters.sort" :title="sortText">
						<view class="slot-content">
							<scroll-view scroll-y="true">
								<up-row gutter="10">
									<up-col span="3" v-for="(item, index) of filterData.options3" :key="index"
										@click="clickSelect(2, item)">
										<view class="select up-line-1" :class="{'active': filters.sort == item.dictValue}">
											{{ item.dictLabel }}</view>
									</up-col>
								</up-row>
							</scroll-view>
						</view>
					</up-dropdown-item>
				</up-dropdown>
			</view>
		</up-sticky>
		<!-- 内容列表 -->

		<scroll-view class="content-list" :class="{'h_auto': !templates.list.length}" scroll-y="true"
			:lower-threshold="50" @scrolltolower="loadMore">
			<view class="grid-container" v-if="templates.list.length">
				<view v-for="(item, index) in templates.list" :key="index" class="grid-item" @click="clickPhoto(item)">
					<view class="photo-card">
						<image class="photo" :src="item.coverUrl" mode="aspectFill" />
						<view class="info">
							<text class="title">{{ item.name }}</text>
							<view class="location">
								<text class="location-text">归属：{{ getOwnTypeName(item.ownType) }}</text>
							</view>
							<view class="bottom-info">
								<text class="price">¥{{ item.price / 100 }}</text>
								<view class="views">
									<uni-icons type="eye" size="12" color="#999999" />
									<text class="views-count">{{ item.usedNum }}人 已使用</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view style="display: block; width: 100%;">
					<up-loadmore status="nomore" nomore-text="没有更多了" fontSize="12" color="#909399" />
				</view>
			</view>
			<up-empty mode="data" iconColor="#EBEEF5" marginTop="100" v-else></up-empty>
		</scroll-view>
		<!-- 底部Tab -->
		<CustomTabBarVue :selected="1" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import CustomTabBarVue from '../../components/CustomTabBar.vue';
	const statusBarHeight = ref(0)
	statusBarHeight.value = uni.getSystemInfoSync()['statusBarHeight']
	
	// 筛选条件
	const filters = reactive({
		location: 0,
		category: 0,
		// sort: 'publishDate',
		sort: 'lastUpdate',
		sex: '2'
	})
	// 筛选条件选项
	const filterData = reactive({
		// 年龄段
		options1: [{
			dictLabel: '全部',
			dictValue: 0
		}],
		// 角色
		options2: [{
			dictLabel: '全部',
			dictValue: 0
		}],
		// 排序
		options3: [
			{
				dictLabel: '最新',
				dictValue: 'publishDate'
			},
			{
				dictLabel: '最热',
				dictValue: 'usedNum'
			}
		],
		// 性别
		options4: [{
				dictLabel: '全部',
				dictValue: '2'
			},
			{
				dictLabel: '男',
				dictValue: '0'
			},
			{
				dictLabel: '女',
				dictValue: '1'
			}
		],
		// 地点
		ownTypes: []
	})
	
	// 搜索栏
	const keyword = ref(null);
	// 上一页面接收的参数
	onLoad((options) => {
		if (options.q) {
			// 扫码进入
			processQRCode(options.q)
		} else {
			const {
				location,
				category
			} = options
			filters.location = location ? location : 0
			filters.category = category ? category : 0
		}
		getTemplates()
	})
	function processQRCode(qrString) {
	    // 解码URL
	    const decodedUrl = decodeURIComponent(qrString);
	    
	    // 提取location参数
	    const locationMatch = decodedUrl.match(/location=([^&]+)/);
	    const stationLocation = locationMatch ? locationMatch[1] : 0;
		
	    // 提取category参数
	    const categoryMatch = decodedUrl.match(/category=([^&]+)/);
	    const stationCategory = categoryMatch ? categoryMatch[1] : 0;
		
		filters.location = stationLocation ? stationLocation : 0
		filters.category = stationCategory ? stationCategory : 0
	}
	  
	// 地点文案
	const locationText = computed(() => {

		if (filterData.options1.length > 1 && filters.location) {
			const label = filterData.options1.filter(item => item.dictValue == filters.location)[0].dictLabel
			return label === '全部' ? '地点' : label
		} else {
			return '地点'
		}
	})

	// 性别文案
	const sexText = computed(() => {
		if (filterData.options4.length > 1 && filters.sex) {
			const label = filterData.options4.filter(item => item.dictValue == filters.sex)[0].dictLabel
			return label === '全部' ? '性别' : label
		} else {
			return '性别'
		}
	})

	// 排序文案
	const sortText = computed(() => {
		if (filterData.options3.length > 1 && filters.sort) {
			return filterData.options3.filter(item => item.dictValue == filters.sort)[0].dictLabel
		} else {
			return '排序'
		}
	})

	// 角色文案
	const categoryText = computed(() => {
		if (filterData.options2.length > 1 && filters.category) {
			const label = filterData.options2.filter(item => item.dictValue == filters.category)[0].dictLabel
			return label === '全部' ? '角色' : label
		} else {
			return '角色'
		}
	})

	// 点击筛选条件
	const filterRef = ref(null)

	function clickSelect(index, item) {
		if (index === 0) {
			filters.location = item.dictValue
		} else if (index === 1) {
			filters.category = item.dictValue
		} else if (index === 2) {
			filters.sort = item.dictValue
		} else if (index === 3) {
			filters.sex = item.dictValue
		}
		filterRef.value.close();
		templates.list = []
		paginationData.value.pageNum =1
		getTemplates()
	}

	onMounted(() => {
		getDictUserType()
		getDictCatType()
		getDictOwnType()
	})

	// 获取套系列表
	const paginationData = ref({
		pageNum: 1,
		pageSize: 10,
		total: 0
	})
	const templates = reactive({
		list: []
	})

	function getTemplates() {
		const params = {}
		if (filters.category != 0) {
			params.catType = filters.category
		}
		if (filters.location != 0) {
			params.ownType = filters.location
		}
		if (filters.sex !== '2') {
			params.userSex = filters.sex
		}
		uni.showLoading({
			title: '加载中...'
		})
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/photos`,
			method: 'GET',
			data: {
				pageNum: paginationData.value.pageNum,
				pageSize: paginationData.value.pageSize,
				orderByColumn: filters.sort,
				isAsc: 'desc',
				...params
			},
			success: (res) => {
				if (res.data.code === 200) {
					templates.list = templates.list.concat(res.data.rows)
					paginationData.value.total = res.data.total
					uni.hideLoading()
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}

	// 滑动加载下一页
	function loadMore() {
		const {
			pageNum,
			pageSize,
			total
		} = paginationData.value
		if (pageNum * pageSize < total) {
			paginationData.value.pageNum += 1
			getTemplates()
		}
	}

	function getOwnTypeName(ownType) {
		const arr = filterData.ownTypes.filter(item => item.dictValue === ownType)
		return arr.length ? arr[0].dictLabel : ''
	}
	// 获取字典-地点
	function getDictOwnType() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/dict/data/list`,
			data: {
				dictType: 'template_own_type',
				status: 0,
				pageNum: 1,
				pageSize: 9999
			},
			method: 'GET',
			success: (res) => {
				if (res.data.code === 200) {
					filterData.ownTypes = res.data.rows
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}

	// 获取字典-人群
	function getDictUserType() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/dict/data/list`,
			data: {
				dictType: 'template_own_type',
				status: 0,
				pageNum: 1,
				pageSize: 9999
			},
			method: 'GET',
			success: (res) => {
				if (res.data.code === 200) {
					filterData.options1 = filterData.options1.concat(res.data.rows)
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}

	// 获取字典-角色
	function getDictCatType() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/dict/data/list`,
			data: {
				dictType: 'template_cat_type',
				status: 0,
				pageNum: 1,
				pageSize: 9999
			},
			method: 'GET',
			success: (res) => {
				if (res.data.code === 200) {
					filterData.options2 = filterData.options2.concat(res.data.rows)
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}

	// 点击查看详情
	function clickPhoto(item) {
		uni.navigateTo({
			url: `/pages/detail/detail?uuid=${item.uuid}`
		})
	}

	// 搜索页
	function toSearch() {
		uni.navigateTo({
			url: `/pages/search/search`
		})
	}
</script>

<style lang="scss" scoped>
	.top-bg {
		background: #FFF5EA;
		.nav-bar {
			height: 84rpx;
			line-height: 84rpx;
			padding: 0 40rpx;
			overflow: hidden;
		}
	}
	.search-box {
		width: 472rpx;
	}

	.dropdown-box {
		background-color: #ffffff;
	}

	::v-deep .u-row {
		flex-wrap: wrap;
	}

	::v-deep .u-flex-row {
		max-width: 177rpx;
	}

	::v-deep .u-dropdown__menu__item__text {
		overflow: hidden;
		white-space: nowrap;
		max-width: 80%;
		text-overflow: ellipsis;
	}

	.slot-content {
		background: #ffffff;
		padding: 20rpx 32rpx;

		.select {
			box-sizing: border-box;
			height: 50rpx;
			line-height: 50rpx;
			font-size: 24rpx;
			color: #303133;
			float: left;
			background: #f4f4f4;
			border-radius: 24rpx;
			margin-right: 20rpx;
			margin-bottom: 20rpx;
			width: 100%;
			text-align: center;

			&.active {
				color: #ffffff;
				background: #E7B796;
			}
		}
	}

	.content-list {
		flex: 1;
		overflow: auto;
		height: calc(100vh - 350rpx);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: border-box;
		&.h_auto {
			height: auto;
		}
	}

	.grid-container {
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx 40rpx 40rpx;
		padding-bottom: env(safe-area-inset-bottom);
		gap: 32rpx;
	}

	.grid-item {
		width: calc(50% - 18rpx);
	}

	.photo-card {
		background-color: #F8F8F8;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.photo {
		width: 100%;
		height: 414rpx;
		display: block;
	}

	.info {
		padding: 12rpx 20rpx;
	}

	.info .title {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.location {
		// margin-top: 4rpx;
	}

	.location-text {
		font-size: 24rpx;
		color: #999999;
	}

	.bottom-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 8rpx;
	}

	.price {
		font-size: 32rpx;
		color: #D19973;
		font-weight: 500;
	}

	.views {
		display: flex;
		align-items: center;
		gap: 4rpx;
	}

	.views-count {
		font-size: 24rpx;
		color: #999999;
	}
</style>